package src.com.server.service;


import src.com.qqcommon.Message;
import src.com.qqcommon.MessageType;
import src.com.server.utility.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

public class SendNewsToAllService implements Runnable{

    @Override
    public void run() {
        // 为了可以多次推送 所以放在循环中
        while (true) {
            System.out.println("请输入服务器要推送的新闻或消息（输入exit表示退出推送服务线程）：");
            String news = Utility.readString(100);
            if (news.equals("exit")) {
                break;
            }
            // 构建一个message对象
            Message message = new Message();
            message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
            message.setSender("服务器");
            message.setContent(news);
            message.setSendTime(new Date().toString());
            System.out.println("服务器给所有人说 " + news);

            // 遍历当前所有在线用户线程
            HashMap<String, ServerConnectClientThread> hm = ManageClientThreads.getHm();

            Iterator<String> iterator = hm.keySet().iterator();
            ObjectOutputStream objectOutputStream = null;
            while (iterator.hasNext()) {
                ServerConnectClientThread serverConnectClientThread = hm.get(iterator.next());
                try {
                    objectOutputStream = new ObjectOutputStream(serverConnectClientThread.getSocket().getOutputStream());
                    objectOutputStream.writeObject(message);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
